﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;

namespace Water.Core
{
    public class DicExpando : DynamicObject
    {
        public DicExpando(Dictionary<string, object> dic)
        {
            members = dic;
        }

        public DicExpando(Hashtable table)
        {
            members = table
                     .Cast<DictionaryEntry>()
                     .ToDictionary(kvp => (string)kvp.Key, kvp => (object)kvp.Value);
        }

        private Dictionary<string, object> members =
                new Dictionary<string, object>();

        /// <summary>
        /// 当添加一个属性,就放到字典中
        /// </summary>     
        public override bool TrySetMember
             (SetMemberBinder binder, object value)
        {
            if (!members.ContainsKey(binder.Name))
                members.Add(binder.Name, value);
            else
                members[binder.Name] = value;

            return true;
        }

        /// <summary>
        /// 当访问属性,到dic中取值
        /// </summary>      
        public override bool TryGetMember
               (GetMemberBinder binder, out object result)
        {
            if (members.ContainsKey(binder.Name))
            {
                result = members[binder.Name];
                return true;
            }
            else
            {
                return base.TryGetMember(binder, out result);
            }
        }

        /// <summary>
        /// 如果属性值是个委托,就调用
        /// </summary>     
        public override bool TryInvokeMember
           (InvokeMemberBinder binder, object[] args, out object result)
        {
            if (members.ContainsKey(binder.Name)
                      && members[binder.Name] is Delegate)
            {
                result = (members[binder.Name] as Delegate).DynamicInvoke(args);
                return true;
            }
            else
            {
                return base.TryInvokeMember(binder, args, out result);
            }
        }


        /// <summary>
        /// 得到所有成员的名字
        /// </summary>
        /// <returns>
        public override IEnumerable<string> GetDynamicMemberNames()
        {
            return members.Keys;
        }
    }
}
